package com.cts.rt.dao.hibernate;

import java.util.List;

import javax.persistence.Table;

import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import com.cts.rt.dao.EmployeeDao;
import com.cts.rt.model.Employee;

/**
 * This class interacts with Hibernate session to save/delete and retrieve User
 * objects.
 * 
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a> Modified by
 *         <a href="mailto:dan@getrolling.com">Dan Kibler</a> Extended to
 *         implement Acegi UserDetailsService interface by David Carter
 *         david@carter.net Modified by <a href="mailto:bwnoll@gmail.com">Bryan
 *         Noll</a> to work with the new BaseDaoHibernate implementation that
 *         uses generics. Modified by jgarcia (updated to hibernate 4)
 */
@Repository("employeeDao")
public class EmployeeDaoHibernate extends GenericDaoHibernate<Employee, Long>
		implements EmployeeDao, UserDetailsService {

	/**
	 * Constructor that sets the entity to User.class.
	 */
	public EmployeeDaoHibernate() {
		super(Employee.class);
	}

	/**
	 * {@inheritDoc}
	 */
	@SuppressWarnings("unchecked")
	public List<Employee> getEmployees() {
		Query qry = getSession().createQuery(
				"from Employee u order by upper(u.username)");
		return qry.list();
	}

	/**
	 * {@inheritDoc}
	 */
	public Employee saveEmployee(Employee employee) {
		if (log.isDebugEnabled()) {
			log.debug("user's id: " + employee.getId());
		}
		getSession().saveOrUpdate(employee);
		// necessary to throw a DataIntegrityViolation and catch it in
		// UserManager
		getSession().flush();
		return employee;
	}

	/**
	 * Overridden simply to call the saveEmployee method. This is happening
	 * because saveUser flushes the session and saveObject of BaseDaoHibernate
	 * does not.
	 * 
	 * @param user
	 *            the user to save
	 * @return the modified user (with a primary key set if they're new)
	 */
	@Override
	public Employee save(Employee employee) {
		return this.saveEmployee(employee);
	}

	/**
	 * {@inheritDoc}
	 */
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		List users = getSession().createCriteria(Employee.class)
				.add(Restrictions.eq("employeeId", username)).list();
		if (users == null || users.isEmpty()) {
			throw new UsernameNotFoundException("user '" + username
					+ "' not found...");
		} else {
			return (UserDetails) users.get(0);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public String getEmployeePassword(Long userId) {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(
				SessionFactoryUtils.getDataSource(getSessionFactory()));
		Table table = AnnotationUtils.findAnnotation(Employee.class,
				Table.class);
		return jdbcTemplate.queryForObject(
				"select password from " + table.name() + " where id=?",
				String.class, userId);
	}
}
